# coding=UTF-8
import argparse


def is_descending(array):
    flag = 0
    for earlier, later in zip(array, array[1:]):
        if later < earlier:
            flag = 1
        elif flag == 1:
            flag = 2  # error!!! 乱序！
    return flag


def main(input_file, output_file, stat):
    infile = open(input_file, 'r')
    if not stat:
        outfile = open(output_file, 'w')

    # 解析TSV文件的行并获取指定列
    desc = 0
    asc = 0
    error = 0

    for line in infile:
        words = line.strip().split("\t")
        readid = words[0]
        pred_pos = [int(x)for x in words[5].split(',')]
        pred_dorado = words[6].split(',')
        pred_deepsignal = words[7].split(',')
        pred_mean = words[8].split(',')
        pred_label = words[9].split(',')
        bis_label = words[15].split(',')
        if len(words) == 17:
            ref_pos = words[16].split(',')
        flag = is_descending(pred_pos)
        # 检查是否为倒序
        if flag == 1:
            # print(f"read {readid} is in descending order. Reversing the order.")
            if not stat:
                pred_pos.reverse()
                pred_dorado.reverse()
                pred_deepsignal.reverse()
                pred_mean.reverse()
                pred_label.reverse()
                bis_label.reverse()
                if len(words) == 17:
                    ref_pos.reverse()
            desc += 1
        elif flag == 0:
            # print(
            #    f"read {readid} is not in descending order. No change needed.")
            asc += 1
        elif flag == 2:
            print(f"read {readid} is in an error order. No change needed.")
            error += 1
            continue
        # print(pred_pos)
        if not stat:
            pred_pos_text = ','.join([str(x) for x in pred_pos])
            pred_dorado_text = ','.join([str(x) for x in pred_dorado])
            pred_deepsignal_text = ','.join([str(x) for x in pred_deepsignal])
            pred_mean_text = ','.join([str(x) for x in pred_mean])
            pred_label_text = ','.join([str(x) for x in pred_label])
            bis_label_text = ','.join([str(x) for x in bis_label])
            if len(words) == 17:
                ref_pos_text = ','.join([str(x) for x in ref_pos])
                fea_str = '\t'.join([readid, words[1], words[2], words[3], words[4], pred_pos_text, pred_dorado_text, pred_deepsignal_text,
                                    pred_mean_text, pred_label_text, words[10], words[11], words[12], words[13], words[14], bis_label_text, ref_pos_text])
            else:
                fea_str = '\t'.join([readid, words[1], words[2], words[3], words[4], pred_pos_text,
                                    pred_dorado_text, pred_deepsignal_text, pred_mean_text, pred_label_text, words[10], words[11], words[12], words[13], words[14],  bis_label_text])
            # 将修改后的列重新组合为一行
            # 保存到新的文件

            outfile.write(fea_str + "\n")
    print('desc:{}, asc:{}, error:{}'.format(desc, asc, error))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='Check and reverse column order in a TSV file.')
    parser.add_argument('--input_file', help='Path to the input TSV file')
    parser.add_argument('--output_file', help='Path to the output TSV file')
    parser.add_argument('--stat', action='store_true',
                        default=False, help="stat mod")

    args = parser.parse_args()

    main(args.input_file, args.output_file, args.stat)
